package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.entity.UserDto;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        log.info("[获取验证码 user:{}]",user);
        String code = ValidateCodeUtils.generateValidateCode(4)+"";
        log.info("验证码:{}",code);

        //把验证码存入session,后续登录时，进行验证
        //session.setAttribute(user.getPhone(),code);
        redisTemplate.opsForValue().set(user.getPhone(),code,5, TimeUnit.MINUTES);
        return R.success("获取验证码成功");
    }

    //验证码登录
    @PostMapping("/login")
    public R<String> login(@RequestBody UserDto userDto,HttpSession session) {
        log.info("[验证码登录 dto:{}，{}]",userDto.getPhone(),userDto.getCode());
        //判断验证码是否正确，不需要强转
        //Object codeInsession = session.getAttribute(userDto.getPhone());
        //从redis中根据手机号取验证码
        Object codeInSession = redisTemplate.opsForValue().get(userDto.getPhone());
        if (codeInSession != null && codeInSession.toString().equals(userDto.getCode())){
            // 2.如果验证通过，偷偷帮用户注册，先去数据库查询一下是否有这个用户，根据手机号一定找到一条记录
            // select * from user where phone = ''
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(User::getPhone,userDto.getPhone());
            //MP用的POJO，Mapper一定用的POJO
            User one = userService.getOne(queryWrapper);
            if (one == null){
                // 数据库中无这条记录，感觉去给注册
                User user = new User();
                user.setPhone(userDto.getPhone());
                // 其它字段，根据产品需求去初始化
                user.setStatus(1);
                userService.save(user);
                // 存盘后，把user的id存入session
                session.setAttribute("user",user.getId());
            }else {
                session.setAttribute("user",one.getId());//对象id存到session
            }
            redisTemplate.delete(userDto.getPhone());
            return R.success("登录成功");
        }
        return R.error("登录失败,验证码无效或过期");
    }
}
